package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.*;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.ServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements ServeService {

    @Resource
    private ServeItemMapper serveItemMapper;
    @Resource
    private RegionMapper regionMapper;
    @Resource
    private ServeTypeMapper serveTypeMapper;
    @Resource
    private ServeSyncMapper serveSyncMapper;

    /**
     * 区域服务分页查询
     *
     * @param servePageQueryReqDTO 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        //调用mapper查询数据，这里由于继承了ServiceImpl<ServeMapper, Serve>，使用baseMapper相当于使用ServeMapper
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryList(
                        servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 区域服务批量新增
     */
    @Override
    public void add(List<ServeUpsertReqDTO> list) {
        //0、校验服务列表是否为空
        if (CollectionUtil.isEmpty(list)) {
            throw new ForbiddenOperationException("服务列表不能为空");
        }
        // 获取城市编码
        List<Long> regionId = list.stream().map(serveUpsertReqDTO -> serveUpsertReqDTO.getRegionId()).collect(Collectors.toList());
        Long regionId2 = regionId.get(0);
        Region region3 = regionMapper.selectById(regionId2);
        //1.校验服务项是否为启用状态，不是启用状态不能新增
        // 第二种方式
        List<Long> ServeItemIdList = list.stream().map(serveUpsertReqDTO -> serveUpsertReqDTO.getServeItemId()).collect(Collectors.toList());
        //                      第一次对数据库进行交互
        List<Serve> serves = listByIds(ServeItemIdList);
        serves.stream().forEach(serve -> {
            if (serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
                throw new ForbiddenOperationException("服务未启用无法添加到区域下使用");
            }
            //2.校验是否重复新增
            list.forEach(serveDTO -> {
                if (Objects.equals(serveDTO.getServeItemId(), serve.getServeItemId()) && Objects.equals(serveDTO.getRegionId(), serve.getRegionId())) {
                    throw new ForbiddenOperationException("服务已存在");
                }
                //3.新增服务
                Serve bean = BeanUtil.toBean(serveDTO, Serve.class);
                bean.setCityCode(region3.getCityCode());
                //  第二次对数据库进行交互
                baseMapper.insert(bean);
            });
        });

            // 第一种方式
//        list.forEach(serveUpsertReqDTO -> {
//            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
//            if(serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()){
//                throw new ForbiddenOperationException("该服务未启用无法添加到区域下使用");
//            }
//            //2.校验是否重复新增
//            Integer count = lambdaQuery()
//                    .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
//                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
//                    .count();
//            if(count > 0){
//                throw new ForbiddenOperationException(serveItem.getName()+"服务已存在");
//            }
//            //3.新增服务
//            Serve bean = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
//            Region region = regionMapper.selectById(bean.getRegionId());
//            bean.setCityCode(region.getCityCode());
//            baseMapper.insert(bean);
//        });
    }

    /**
     * 修改价格
     */
    @CachePut(value = RedisConstants.CacheName.SERVE, key = "#id",cacheManager = RedisConstants.CacheManager.ONE_DAY)
    @Override
    public Serve updatePrice(Long id, BigDecimal price) {
        if (id == null || price == null) {
            throw new ForbiddenOperationException("参数不能为空");
        }
        // 服务上架状态不能修改
        Serve serve = baseMapper.selectById(id);
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务上架状态不能修改");
        }
        // 更新服务价格
        boolean update = lambdaUpdate().set(Serve::getPrice, price).eq(Serve::getId, id).update();
        if (!update) {
            throw new ForbiddenOperationException("服务价格修改失败");
        }
        return serve;
    }

    /**
     * 上架服务
     * @Cacheable 查询数据时缓存，将方法的返回值进行缓存
     * @CachePut 用于更新缓存，将方法的返回值放到缓存中
     */
//    @Cacheable(value = RedisConstants.CacheName.SERVE,key = "#id",cacheManager = RedisConstants.CacheManager.ONE_DAY)
    @Cacheable(value = RedisConstants.CacheName.SERVE, key = "#id",cacheManager = RedisConstants.CacheManager.ONE_DAY)
    @Override
    @Transactional
    public Serve onSale(Long id) {
        if (id != null) {
            Serve serve = baseMapper.selectById(id);
            // 判断是否已上架
            if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
                throw new ForbiddenOperationException("服务已上架");
            }
            ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
            // 判断服务是否启用
            if (serveItem.getActiveStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
                serve.setSaleStatus(FoundationStatusEnum.ENABLE.getStatus());
                baseMapper.updateById(serve);
            } else {
                throw new ForbiddenOperationException("该服务未启用无法上架");
            }
        }
        //添加同步表
        addServeSync(id);
        return getById(id);
    }

    /**
     * 新增服务同步数据
     */
    private void addServeSync(Long serveId) {
        //服务信息
        Serve serve = baseMapper.selectById(serveId);
        //区域信息
        Region region = regionMapper.selectById(serve.getRegionId());
        //服务项信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        //服务类型
        ServeType serveType = serveTypeMapper.selectById(serveItem.getServeTypeId());

        ServeSync serveSync = new ServeSync();
        serveSync.setServeTypeId(serveType.getId());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeSortNum(serveType.getSortNum());

        serveSync.setServeItemId(serveItem.getId());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setPrice(serve.getPrice());

        serveSync.setCityCode(region.getCityCode());
        serveSync.setId(serve.getId());
        serveSync.setIsHot(serve.getIsHot());
        serveSyncMapper.insert(serveSync);
    }

    /**
     * 删除服务
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        if (id == null) {
            throw new ForbiddenOperationException("参数不能为空");
        }
        Serve serve = baseMapper.selectById(id);
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务已上架，不能删除");
        } else {
            baseMapper.deleteById(id);
        }
    }

    /**
     * 下架服务
     * @CacheEvict 用于删除缓存，将一条或多条数据从缓存中删除。
     */
    @CacheEvict(value = RedisConstants.CacheName.SERVE,key = "#id")
    @Override
    @Transactional
    public Serve offSale(Long id) {
        if (id == null) {
            throw new ForbiddenOperationException("参数不能为空");
        }
        Serve serve = baseMapper.selectById(id);
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            serve.setSaleStatus(FoundationStatusEnum.DISABLE.getStatus());
            baseMapper.updateById(serve);
        }
        //删除同步表的数据
        serveSyncMapper.deleteById(id);
        return getById(id);
    }

    /**
     * 设置热门开发
     */
    @Override
    public void onHot(Long id) {
        if (id == null) {
            throw new ForbiddenOperationException("参数不能为空");
        }
        Serve serve = baseMapper.selectById(id);
        // 判断是否已上架
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务上架状态，不能修改");
        }
        // 判断是否是热门
        if (serve.getIsHot() == 1) {
            throw new ForbiddenOperationException("服务已设为热门，不能重复设置");
        }
        serve.setIsHot(1);
        baseMapper.updateById(serve);
    }

    /**
     * 取消热门
     */
    @Override
    public void offHot(Long id) {
        if (id == null) {
            throw new ForbiddenOperationException("参数不能为空");
        }
        Serve serve = baseMapper.selectById(id);
        // 判断是否已上架
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务上架状态，不能修改");
        }
        // 判断是否是热门
        if (serve.getIsHot() == 0) {
            throw new ForbiddenOperationException("服务已设为非热门，不能重复设置");
        }
        serve.setIsHot(0);
        baseMapper.updateById(serve);
    }

    /**
     * 根据ID查询服务详情
     */
    @Override
    public ServeAggregationResDTO findServeDetailById(Long id) {
        return baseMapper.findServeDetailById(id);
    }
}
